const { Order, OrderItem } = require("../models/order");
const { Good, Sku } = require("../models/good");
const { Address } = require("../models/appUser");
// 获取所有订单
getAllOrders = async (req, res) => {
  try {
    const orders = await Order.findAll({
      include: [
        {
          model: OrderItem,
          include: {
            all: true,
          },
        },
      ],
    });
    for (let i = 0; i < orders.length; i++) {
      const address = await Address.findOne({
        where: { id: orders[i].addressId },
      });
      orders[i].address = address;
    }
    res.status(200).json({
      orders: orders,
      code: 200,
    });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 根据ID获取订单
getOrderById = async (req, res) => {
  try {
    const order = await Order.findOne({
      where: { id: req.params.id },
      include: [
        {
          model: OrderItem,
          include: [
            {
              model: Good,
              attributes: ["name", "price"],
            },
            {
              model: Sku,
              attributes: ["name", "amount", "stock_quantity"],
            },
          ],
        },
      ],
    });
    if (order) {
      res.status(200).json({
        order: order,
        code: 200,
      });
    } else {
      res.status(404).json({ error: "Order not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// 修改订单状态为已发货
shipOrder = async (req, res) => {
  const appUserId = req.userId;
  const { id } = req.params;
  const { delivery } = req.body;
  try {
    const order = await Order.findOne({
      where: {
        id: id,
        appUserId: appUserId,
      },
    });
    if (order) {
      await order.update({
        status: "已发货",
        delivery: delivery,
      });
      res.status(200).json({
        message: "Order status updated successfully",
        data: order,
        code: 200,
      });
    } else {
      res.status(404).json({ error: "Order not found" });
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

module.exports = {
  createOrder,
  getAllOrders,
  getOrderById,
  changeOrderStatus,
  shipOrder,
};
